/**
 * 知识库搜索实现
 */
var knowledgeSearch = function() {
	var $searchHelpBtn = $("#searchHelpBtn");
	var $body = $("body");
	var $search = $('#search');
	var $searchInput = $("#searchInput");
	
	// 1. 聚焦搜索框
	$searchInput.focus();
	var lastQueryString = '';
	
	$searchInput.dropList({
		"onRenderItem":function(index,item,$a){ // 非必须
			$a.attr("href", 'javascript:void(0)');
			// ctx + "/sms/knowledge/knowledgeRepos/id/" + item['question_id']
			$a.on('click', function(e) {
				e.stopPropagation();
				e.preventDefault();
				var url = ctx + "/sms/knowledge/repos/showx/" + item['question_id'];
				mftabset.activeMenu(item['question_id'], '详情：' + item['title'], url);
			});
			return $a;
		},
	 	"contentDefine":{
	 		"id":"question_id",
	 		"text":"title"
	 	},
	 	"ajaxSetting":function(){
	 		return {
	 			"type":"POST",
	 			"url":ctx + "/sms/knowledge/repos/search",
	 			"data":{
	 				'searchKey': $searchInput.val(),
	 			},
	 			"success":function(data,status,xhr){
	 			}
	 		};
	 	},
	 	"cssClass":"t-search-droplist",
	 	"silent":true, // 非必须
	 	"autocomplete":true, // 非必须
	 	"onEnterKeyDown": function(val) { // enter键按下时触发的事件，非必须
	 		var id = $.zui.uuid();
	 		var name = '搜索：' + val;
	 		var url = ctx + "/sms/knowledge/repos/search/index/" + encodeURI(val);
	 		if (!StringUtil.isBlank(val)) {
	 			// if val is empty, 不处理
	 			mftabset.activeMenu(id, name, url);
	 		}
	 		return {
	 			'doRemove': true
	 		};
	 	}
	});
	
	// 重置查询
	var resetQuery = function(){
		$searchInput.val(''); // 置空
		$("#search").removeClass("with-query-text");
        $body.removeClass('query-enabled').attr('data-query', '');
	};
	// 2. 事件绑定
	$searchInput.on('change keyup paste input propertychange', function(){
		var val = $searchInput.val();
		$("#search").toggleClass('with-query-text', val.length > 0); // 根据内容，右边的按钮样式发生改变
	}).on('keydown',function(e){
		if( e.which == 27) {
			// Esc 键
			resetQuery();
		}
	}).on('focus', function() {
        $body.addClass('input-query-focus');
    }).on('blur', function() {
        $body.removeClass('input-query-focus');
    }).on('click', function(e){
    	e.stopPropagation();
    });
	// 搜索输入框右侧，清除搜索内容按钮事件绑定
	$searchHelpBtn.on('click',function(e){
		if($search.hasClass('with-query-text')) {
			resetQuery();
			$searchInput.focus();
            $search.removeClass('with-query-text');
        } else {
            $(this).blur();
        }
	});
};
var Keyboard={
	// 绑定按键事件
	bindKeyEvent:function(){
		$(window).on('keydown',function(e){
			var code = e.which;
            var isDoubleView = $("body").hasClass('view-double');
            var isInputFocus = $("body").hasClass('input-query-focus');
            var $searchInput = $("#searchInput");
            
            if(code === 9) { // Tab
                if(!$("body").hasClass('input-query-focus') && !$("body").hasClass("modal-open")
                		&& $searchInput.length > 0) {
                	$searchInput.focus();
                    e.preventDefault();
                }
            } else if(code === 27) { // Esc
                if(PageLayoutSwith.isDoubleView()) {
                    if(!isInputFocus) {
                    	$searchInput.focus();
                    }
                    SearchInput.lastQueryString='';
                    SearchInput.query();
                }
            }
		});
	}
};
// KnowledgeReposPage页面上
var KnowledgeReposPage = {
	'onQueryCategoriesSucc': function(data, status, xhr) {
		// Logger.warn("data => " + JSON.stringify(data));
	},
	'onCategoryItemSelected': function(node) {
		Logger.warn("item node => " + JSON.stringify(node));
		// categoriesTree.search("2-1");
		if (node.type == 'category') {
			mftabset.activeMenu(node.id, node.name, ctx + '/sms/knowledge/repos/search/index/' + node.id + '?category='+node.id);
		}
		if (node.type == 'group') {
			
		}
	},
	'activeMenu': function(id, name, url) {
		mftabset.activeMenu(id, name, url);
	}
};

$(function(){
	// 低版本浏览器提醒
	if($.zui.browser.ie && $.zui.browser.ie < 11) {
        $.zui.messager.danger('你正在使用 IE 较低版本访问，无法获得 ZUI 文档网站的完整体验，建议你更换浏览器再访问。', {time: 20000});
    }
	try{
		// 启用日志记录器
		Logger.hide(); // 隐藏日志记录器
		if(Logger.enable){
			$(window).on('keydown',function(e){
				var code = e.keyCode;
				if(code == 120) { // F9 按键
					Logger.toggle();
					return ;
				}
				if(code == 115) { // F4 按键
					Logger.close();
					return ;
				}
			});
		}
		// SearchInput.init();// 搜索框初始化
		knowledgeSearch(); // 知识库搜索
		Keyboard.bindKeyEvent(); // 绑定键盘按键事件
	}catch(e){
		Logger.error("page init failed, doc.js error:");
		Logger.error(e);
	}
	
	var $pageContent = $("#pageContent");
	var $searchInput = $("#searchInput");
	var $exactQueryKey = $("#exactQueryKey");
	var $questionName = $("#questionName");
	
	var searchKey = $searchInput.val();
	var exactQueryKey = $exactQueryKey.val();
	
	// Logger.warn("searchKey = " + searchKey);
	// Logger.warn("exactQueryKey = " + exactQueryKey);
	
	var id = 'home';
	var name = '搜索:' + $searchInput.val();
		
	var url = null;
	if (searchKey) {
		// 模糊查询
		url = ctx + "/sms/knowledge/repos/search/index/" + $searchInput.val();
	} else if (exactQueryKey) {
		// 精确
		url = ctx + "/sms/knowledge/repos/showx/" + $exactQueryKey.val();
		id = $exactQueryKey.val();
		name = '详情:' + $questionName.val();
		$exactQueryKey.val('');
	} else {
		// 默认打开
		url = ctx + "/sms/knowledge/repos/searchPrompt";
	}
	window.mftabset = $pageContent.ftabset({
		defaultTabData: [{
			'id':id,
			'name':name,
			'url':url,
			'active': true
		}]
	});
	var moveEnd = function(obj){
		obj.focus(); 
		var len = obj.value.length; 
		if (document.selection) { 
			var sel = obj.createTextRange(); 
			sel.moveStart('character',len); 
			sel.collapse(); 
			sel.select(); 
		} else if (typeof obj.selectionStart == 'number' && typeof obj.selectionEnd == 'number') { 
			obj.selectionStart = obj.selectionEnd = len; 
		} 
	};
	moveEnd($searchInput[0]);
	var $searchKnowledgeInput = $("#searchKnowledgeInput");
	$searchKnowledgeInput.on('change keyup paste input propertychange', function(){
		var searchKey = $(this).val();
		categoriesTree.search(searchKey);
	});
});